import store from '../store'
import config from '../config'
import {
	isEmpty,
} from '../utils'

const requests = {}

const ajax = (params = {}) => {
	return new Promise(async (resolve, reject) => {
		let errMsg = ''
		if (!params.url) {
			errMsg = '请求地址不能为空'
			uni.showModal({
				title: errMsg,
				showCancel: false
			})
			return reject({
				message: errMsg
			})
		}
		// 参数合并
		params = Object.assign({
			method: 'GET',
			baseURL: config.baseURL,
			data: {},
			header: {
				token: store.state.user.token
			},
			__errorHandle: true, // 自动处理错误
		}, params)
		params.method = params.method.toLocaleUpperCase()
		// 无网络的时候报错
		if (store.state.event.netWorkType === 'none') {
			errMsg = '无网络连接'
			uni.showToast({
				icon: 'none',
				title: errMsg
			})
			return reject({
				message: errMsg
			})
		}
		// 防抖处理
		if (!['GET', 'OPTIONS'].includes(params.method)) {
			const now = Date.now()
			if (requests[params.url] && now - requests[params.url] <= 500) {
				errMsg = `操作过于频繁${params.url}`
				uni.showToast({
					icon: 'none',
					title: errMsg
				})
				return reject({
					message: errMsg
				})
			}
			requests[params.url] = now
		}
		if (!(/:\/\//.test(params.url) || /^\/\//.test(params.url))) {
			params.url = params.baseURL.replace(/\/$/, '') + '/' + params.url.replace(/^\//, '')
		}
		const {
			data
		} = params
		const query = {}
		for (const key in data) {
			let item = data[key]
			if (!isEmpty(item)) {
				if (typeof item === 'string') {
					item = item.trim()
				}
				query[key] = item
			}
		}
		let model = uni.request
		let args = {
			...params,
			data: query
		}
		if (params.method === 'UPLOAD') {
			model = uni.uploadFile
			args = {
				...params,
				...query
			}
		}
		return model({
			...args,
			success({
				data
			}) {
				if (typeof data === 'string') {
					try {
						data = JSON.parse(data)
					} catch (e) {}
				}
				return resolve(data)
				if (1==data.error || -1==data.error) {
					errMsg = data.msg
					if (params.__errorHandle) {
						uni.showToast({
							icon: 'none',
							title: errMsg
						})
						if(-1==data.error){
							setTimeout(() => {
								return uni.navigateTo({
									url: '/pages/user/login/code'
								})
							}, 300)
						}
					}
					return reject({
						message: errMsg
					})
				} else {  
					return resolve(data)
				}
			},
			fail(e) {
				errMsg = e.errMsg
				uni.showModal({
					content: errMsg,
					title: '请求失败',
					showCancel: false
				})
				return reject({
					message: errMsg
				})
			}
		})
	})
}

['get', 'post', 'put', 'delete', 'head', 'upload'].map(method => {
	ajax[method] = (url, params = {}) => {
		params = Object.assign({
			data: params
		}, {
			url
		}, {
			method: method.toLocaleUpperCase()
		})
		return ajax(params)
	}
})

export default ajax